package com.hsylient.javase.chapter12.demo01.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.Scanner;

//客户端A
public class ChatA {
	public static void main(String[] args) {
		//控制台输入
		Scanner input = new Scanner(System.in);
		
		// 创建基于UDP协议的DatagramSocket对象
		// 客户端A监听8888端口
		try (DatagramSocket socket = new DatagramSocket(8888)) {
			//封装成DatagramPacket对象(数据包)
			DatagramPacket sendPacket = new DatagramPacket(
					new byte[1024],
					1024,
					new InetSocketAddress("192.168.1.104", 7777));//对方的IP地址和端口号
			DatagramPacket receivePacket = new DatagramPacket(new byte[1024], 1024);
			while (true) {
				// 发送数据包
				System.out.print("我: ");
				String sendContent = input.nextLine();
				sendPacket.setData(sendContent.getBytes());
				socket.send(sendPacket);
				if (sendContent.equals("over")) {
					System.out.println("你退出了聊天......");
					break;
				}
				// 接收数据包
				socket.receive(receivePacket);
				String receiveContent = new String(
						receivePacket.getData(),   //数据
						receivePacket.getOffset(), //读取位置
						receivePacket.getLength());//长度
				if (receiveContent.equals("over")) {
					System.out.println("对方退出了聊天......");
					break;
				}
				System.out.println("孟令军: " + receiveContent);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

